angular.module('swan.service.authorService', [])
.factory('authorFactory', ['$window','$rootScope','$cookies', function($window,$rootScope,$cookies) {
    var currentUser = $cookies.getObject('user') || {};
    
    var setUser = function(user) {
    	$cookies.remove('user');
        currentUser = {};
        angular.extend(currentUser, user);

        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + 1);//设置cookie保存30天
        //expireDate.setSeconds(expireDate.getSeconds() + 100000000);

        $cookies.putObject('user', currentUser, {
            'expires': expireDate
        });
    };

    return {
        setUser: setUser,
        getUser: function() {
            return currentUser;
        },
        setToken: function(token) {
        	$window.sessionStorage && $window.sessionStorage.setItem('token-storage', token);
        },
        getToken: function() {
            return $window.sessionStorage.getItem('token-storage');
        },
        setUserId: function(userId) {
        	$window.sessionStorage && $window.sessionStorage.setItem('userId-storage', userId);
        },
        getUserId: function() {
            return $window.sessionStorage.getItem('userId-storage');
        },
        setToState: function(state) {
            if (state == "^") {
            } 
            else {
            	currentUser.toUrl = state;
                //setUser(currentUser);
                //angular.extend(currentUser, currentUser);
            }
        },
        getToState: function() {
            return currentUser.toUrl;
        },
        setFromState: function(state) {
            if (state == "^") {
            } 
            else {
            	currentUser.fromUrl = state;
                //setUser(currentUser);
            }
        },
        getFromState: function() {
            return currentUser.fromUrl;
        },
        setDynamicMenu: function(menu) {
            var menuJson = JSON.stringify(menu);
            $window.sessionStorage && $window.sessionStorage.setItem('menuList-storage', menuJson);
        },
        getDynamicMenu: function() {
        	var menuJson = $window.sessionStorage.getItem('menuList-storage');
        	return JSON.parse(menuJson);
        },
        login: function(user, success, error) {
            setUser(user);
            success();
        },
        logout: function(success, error) {
            $cookies.remove('user');
            currentUser = {};
        	$window.sessionStorage && $window.sessionStorage.removeItem('userId-storage');
        	$window.sessionStorage && $window.sessionStorage.removeItem('token-storage');
        	$window.sessionStorage && $window.sessionStorage.removeItem('menuList-storage');
            success();
        }
    };
}]);
